package a66weding.com.jiehuntong.activity;

import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.LogoPosition;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiCitySearchOption;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;

import java.util.ArrayList;
import java.util.List;

import a66weding.com.jiehuntong.R;
import a66weding.com.jiehuntong.activity.home.BaseHomeActivity;
import a66weding.com.jiehuntong.adapter.CommonAdapter;
import a66weding.com.jiehuntong.adapter.ViewHolder;
import a66weding.com.jiehuntong.beans.AddressBean;
import a66weding.com.jiehuntong.common.utils.CUtils;
import a66weding.com.jiehuntong.common.utils.LogUtil;
import a66weding.com.jiehuntong.common.utils.Tools;
import a66weding.com.jiehuntong.common.utils.Utils;
    public class WeddingAddressActivity extends BaseHomeActivity implements View.OnClickListener {
    private EditText et_soso_map;
    private ImageView img_delete_sosotext;
    private MapView wedding_address_map;
    private PoiSearch mPoiSearch;
    private TextView tv_soso_map;
    private BaiduMap mBaiduMap;
    private ListView lv_address_all;
    private RelativeLayout rl_map;
    private String mLastAaddress;
    private String mCity;
    private GeoCoder mSearch;
    private String address;
    // 第二步，创建POI检索监听者；(结果回调在这里)
    OnGetPoiSearchResultListener poiListener = new OnGetPoiSearchResultListener(){
        public void onGetPoiResult(PoiResult poiResult){//获得检索结果
            List<PoiInfo> allPoi = poiResult.getAllPoi();//获得全部的搜索信息
            if(allPoi!=null){//判断本次搜索是否为空
                 ArrayList<AddressBean> addresses = new ArrayList<>();//本次搜索需要的数据集合
                for (PoiInfo poiInfo : allPoi) {
                    String name = poiInfo.name;
                    String address = poiInfo.address;
                    LatLng location = poiInfo.location;
                    addresses.add(new AddressBean(name,address,location));
                }
                setDate2List(addresses);
                if (mPoiSearch!=null){
                    mPoiSearch.destroy();
                }
                Tools.dismissWaitDialog();
                tv_soso_map.setEnabled(true);
            }else {
                if (mCity.equals("中国")){//如果搜索的城市中达到了中国
                    //在尝试一次在搜索内容加入中国尝试一次
                    if (address!=null&&!address.startsWith("中国")){
                        address=  "中国"+address;
                        Log.i("951", "d: "+address);
                        sosoBaiduMapFromCountry(address);
                    }else {//如果都达到了中国则放弃
                        if (!address.contains("市")&&!address.contains("县")){
                            CUtils.showToast("请您加入城市全名成后,再次尝试!");
                        }else{
                            CUtils.showToast("您所搜的目标有可能太小,\n选择一个更大的目标更容易搜索到呢!\n或更换关键字再次尝试也可以哦!");
                        }
                        if (mPoiSearch!=null){
                            mPoiSearch.destroy();
                        }
                        tv_soso_map.setEnabled(true);
                        Tools.dismissWaitDialog();
                    }
                }else {
                    sosoBaiduMap(false);
                }
            }
        }
        public void onGetPoiDetailResult(PoiDetailResult result){ }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //在调用一次
        SDKInitializer.initialize(getApplicationContext());
        setContentView(R.layout.activity_wedding_address);
        initView();
        //更改百度logo的位置
        wedding_address_map.setLogoPosition(LogoPosition.logoPostionRightBottom);
    }
    private void initView() {
        /*头部状态栏*/
        TextView tv_tools_dayplan_backcontent = (TextView) findViewById(R.id.tv_tools_dayplan_backcontent);
        LinearLayout llay_toolsheader_back = (LinearLayout) findViewById(R.id.llay_toolsheader_back);
        TextView tv_tools_dayplan_title = (TextView) findViewById(R.id.tv_tools_dayplan_title);
        TextView tv_tools_dayplan_addtype1 = (TextView) findViewById(R.id.tv_tools_dayplan_addtype1);
        ImageView img_tools_dayplan_backcontent = (ImageView) findViewById(R.id.img_tools_dayplan_backcontent);
        img_tools_dayplan_backcontent.setOnClickListener(this);
        tv_tools_dayplan_backcontent.setText("     ");
        tv_tools_dayplan_title.setText("选择地址");
        tv_tools_dayplan_addtype1.setText("保存");
        tv_tools_dayplan_addtype1.setVisibility(View.VISIBLE);
        tv_tools_dayplan_backcontent.setOnClickListener(this);
        llay_toolsheader_back.setOnClickListener(this);
        tv_tools_dayplan_backcontent.setOnClickListener(this);
        tv_tools_dayplan_addtype1.setOnClickListener(this);

        /*底部内容信息*/
        et_soso_map = (EditText) findViewById(R.id.et_soso_map);
        tv_soso_map = (TextView) findViewById(R.id.tv_soso_map);
        lv_address_all = (ListView) findViewById(R.id.lv_address_all);
        tv_soso_map.setOnClickListener(this);
        img_delete_sosotext = (ImageView) findViewById(R.id.img_delete_sosotext);
        wedding_address_map = (MapView) findViewById(R.id.wedding_address_map);
        rl_map = (RelativeLayout) findViewById(R.id.rl_map);
        mBaiduMap= wedding_address_map.getMap();
        //获取跳转时候带过来的地理位置信息
        Intent intent = getIntent();
        double mLongitude = intent.getDoubleExtra("longitude", 0);
        double mLatitude = intent.getDoubleExtra("latitude", 0);
        mLastAaddress = intent.getStringExtra("address");
        if(mLongitude != 0 && mLatitude != 0){
            LatLng location = new LatLng(mLatitude, mLongitude);
            //设置地图显示位置
            MapStatusUpdate mapStatusUpdate = MapStatusUpdateFactory.newLatLngZoom(location, 17);
            mBaiduMap.setMapStatus(mapStatusUpdate);
            et_soso_map.setText(mLastAaddress);//设置搜索框为当前使用的地理位置信息
            et_soso_map.setSelection(et_soso_map.getText().length());
    }
        //   MapStatus mapStatus = mBaiduMap.getMapStatus();
        //  LatLng target = mapStatus.target;
        // getAddress(target);//获得当前中心点的位置信息
        mBaiduMap.setOnMapStatusChangeListener(new BaiduMap.OnMapStatusChangeListener() {
            @Override
            public void onMapStatusChangeStart(MapStatus mapStatus) {
            }
            @Override
            public void onMapStatusChange(MapStatus mapStatus) {
            }
            @Override
            public void onMapStatusChangeFinish(MapStatus mapStatus) {
                LogUtil.i("6969","------完成-------");
                LatLng target = mapStatus.target;
                getAddress(target);
            }
        });
        wedding_address_map.setOnClickListener(this);
        img_delete_sosotext.setOnClickListener(this);
        et_soso_map.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }
            @Override
            public void afterTextChanged(Editable s) {
                if (mPoiSearch!=null){
                    mPoiSearch.destroy();
                }
                if (mSearch!=null){
                    mSearch.destroy();
                }
                tv_soso_map.setEnabled(true);
                if(et_soso_map.getText().toString().length()>0){
                    img_delete_sosotext.setVisibility(View.VISIBLE);
                }else {
                    img_delete_sosotext.setVisibility(View.GONE);
                }
            }
        });
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.llay_toolsheader_back:
                this.finish();
                break;
            case R.id.img_tools_dayplan_backcontent:
                this.finish();
                break;
            case R.id.tv_tools_dayplan_backcontent:
                this.finish();
                break;
            case R.id.tv_tools_dayplan_addtype1:
                Intent intent = new Intent();
                intent.putExtra("address",mLastAaddress);
                intent.putExtra("latitude",mBaiduMap.getMapStatus().target.latitude);
                intent.putExtra("longitude",mBaiduMap.getMapStatus().target.longitude);
                setResult(9,intent);
                finish();
                break;
            case R.id.img_delete_sosotext://点击删除的图标删除所有的编辑框中的字体
                et_soso_map.setText("");
                if(lv_address_all.getVisibility() == View.VISIBLE){
                    lv_address_all.setVisibility(View.GONE);
                }
                break;
            case R.id.tv_soso_map:
                Tools.showWaitDialog(this,null, true);
                Utils.hideSoftInputWindow(WeddingAddressActivity.this);
                sosoBaiduMap(true);
                tv_soso_map.setEnabled(false);
                break;
            case R.id.wedding_address_map:
                break;

        }
    }
    /**
     * 搜索地图功能
     */
    private void sosoBaiduMap( boolean isCity) {
        address = et_soso_map.getText().toString().replaceAll("/s", "");
        if (TextUtils.isEmpty(address)){
            CUtils.showToast("检索内容不能为空");
        }else {
            if (isCity) {
                sosoBaiduMapFromCity(address);
            }else {
                sosoBaiduMapFromCountry(address);
            }
        }
    }

    private void sosoBaiduMapFromCountry(String soso) {
        Log.i("951",mCity+ "搜索:"+soso);
        mCity = "中国";
        // 第一步，创建POI检索实例
        mPoiSearch = PoiSearch.newInstance();
        // 第三步，设置POI检索监听者；
        mPoiSearch.setOnGetPoiSearchResultListener(poiListener);
        //   第四步，发起检索请求；
        mPoiSearch.searchInCity(new PoiCitySearchOption().city(mCity).keyword(soso));
    }
    /**
     * 根据经纬度查询地址信息
     */

    private void sosoBaiduMapFromCity(final String soso) {
        //第一步，创建地理编码检索实例；
        mSearch = GeoCoder.newInstance();
        // 第二步，创建地理编码检索监听者；(地里查询结果在这里)
        OnGetGeoCoderResultListener listener = new OnGetGeoCoderResultListener() {
            public void onGetGeoCodeResult(GeoCodeResult result) {
                if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
                    //没有检索到结果
                }
                mSearch.destroy();
                //获取地理编码结果
            }
            @Override
            public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) {    //获取反向地理编码结果
                mSearch.destroy();
                //没有找到检索结果
                if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
                    mCity = "中国";
                    sosoBaiduMapFromCountry(soso);
                }
                else {
                    ReverseGeoCodeResult.AddressComponent addressDetail = result.getAddressDetail();
                    mCity =  addressDetail.city;
                    if (TextUtils.isEmpty(mCity)){//如果城市为空,就获取省份为城市
                        mCity = addressDetail.province;
                    }
                    if (TextUtils.isEmpty(mCity)){//如果省份仍然为空,默认中国(这种情况估计为0)以防万一
                        mCity = "中国";
                    }
                    Log.i("951",mCity+ "搜索:"+soso);
                    //-------------------------这里才是真正要搜索的-----------------------------------------
                    // 第一步，创建POI检索实例
                    mPoiSearch = PoiSearch.newInstance();
                    // 第三步，设置POI检索监听者；
                    mPoiSearch.setOnGetPoiSearchResultListener(poiListener);
                    //   第四步，发起检索请求；
                    mPoiSearch.searchInCity(new PoiCitySearchOption().city(mCity).keyword(soso));
                }
            }
        };
        LatLng lat = mBaiduMap.getMapStatus().target;//获取当前地图中心点的坐标
        ReverseGeoCodeOption rgco = new ReverseGeoCodeOption().location(lat);
        //第三步，设置地理编码检索监听者；
        mSearch.setOnGetGeoCodeResultListener(listener);
        // 第四步，发起地理编码检索；
        mSearch.reverseGeoCode(rgco);
    }

    private void  getAddress(LatLng lat){
        //第一步，创建地理编码检索实例；
           mSearch = GeoCoder.newInstance();
//       第二步，创建地理编码检索监听者；(地里查询结果在这里)
        OnGetGeoCoderResultListener listener = new OnGetGeoCoderResultListener() {
            private String city;

            public void onGetGeoCodeResult(GeoCodeResult result) {
                if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
                    //没有检索到结果
                }
                //获取地理编码结果
            }
            @Override
            public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) {    //获取反向地理编码结果
                if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
                    //没有找到检索结果
                }else {
                    ReverseGeoCodeResult.AddressComponent addressDetail = result.getAddressDetail();
                     city =  addressDetail.city;
                    String address = result.getAddress();
                    List<PoiInfo> poiList = result.getPoiList();//这是附近的兴趣点信息
                    if (poiList!=null){
                       // mLastAaddress=address+poiList.get(0).name;
                        mLastAaddress=poiList.get(0).name;
                    }else {
                        mLastAaddress=address;
                    }
                    et_soso_map.setText(mLastAaddress);
                    et_soso_map.setSelection(et_soso_map.getText().length());
                }
            }
        };
        ReverseGeoCodeOption rgco = new ReverseGeoCodeOption().location(lat);
        //第三步，设置地理编码检索监听者；
        mSearch.setOnGetGeoCodeResultListener(listener);
        // 第四步，发起地理编码检索；
        mSearch.reverseGeoCode(rgco);
    }
    /**
     * 根据经纬度查询城市
     */
    private void setDate2List(final ArrayList<AddressBean> addresses) {
        //ListView适配器适配搜索后的数据
        CommonAdapter<AddressBean> addressBeanCommonAdapter = new CommonAdapter<AddressBean>(getApplicationContext(), addresses, R.layout.item_show_wedding_address) {
            @Override
            public void convert(ViewHolder holder, AddressBean addressBean) {
                holder.setText(R.id.tv_name, addressBean.getName());
                holder.setText(R.id.tv_address, addressBean.getAddress());
            }
        };
        //将百度地图设置为不显示并显示ListView显示搜索数据
        rl_map.setVisibility(View.GONE);
        lv_address_all.setVisibility(View.VISIBLE);
        //设置适配器
        lv_address_all.setAdapter(addressBeanCommonAdapter);
        //ListView设置条目点击事件
        lv_address_all.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                AddressBean addressBean = addresses.get(position);
                LatLng location = addressBean.getLocation();
                if (location!=null){
                    lv_address_all.setVisibility(View.GONE);
                    rl_map.setVisibility(View.VISIBLE);
                    //设位置
                    setUserMapCenter(location);
                    mLastAaddress=addressBean.getName();
                    et_soso_map.setText(mLastAaddress);
                    et_soso_map.setSelection(et_soso_map.getText().length());
                 //  mLastAaddress=   addressBean.getAddress()+addressBean.getName();
                    mLastAaddress=  addressBean.getName();
                    LogUtil.i("444", "地址:"+mLastAaddress);
                    LogUtil.i("444", "latitude:"+location.latitude);
                    LogUtil.i("444", "longitude:"+location.longitude);
                }else {
                    CUtils.showToast("您选择的不是一个具体的地理位置");
                }
            }
        });
    }
    /**
     * 设置地图中心点
     */
    private void setUserMapCenter(LatLng cenpt ) {
//        LatLng cenpt = new LatLng(lat,lon);
        //定义地图状态
        MapStatus mMapStatus = new MapStatus.Builder()
                .target(cenpt)
                .zoom(17)
                .build();
        //定义MapStatusUpdate对象，以便描述地图状态将要发生的变化
        MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
        //改变地图状态
        mBaiduMap.setMapStatus(mMapStatusUpdate);
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        wedding_address_map.onDestroy();
        if (mPoiSearch!=null){
            mPoiSearch.destroy();
        }
        if (mSearch!=null){
            mSearch.destroy();
        }
    }
    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        wedding_address_map.onResume();
    }
    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        wedding_address_map.onPause();
    }

    @Override
    public void onBackPressed() {
        if(lv_address_all.getVisibility() == View.VISIBLE){
            lv_address_all.setVisibility(View.GONE);
            if (rl_map.getVisibility()==View.GONE){
                rl_map.setVisibility(View.VISIBLE);
            }
            return;
        }
        super.onBackPressed();
    }
}

